package com.artezio.buyndrive.web;

import com.artezio.buyndrive.domain.Admin;
import com.artezio.buyndrive.domain.Carservice;
import com.artezio.buyndrive.domain.Country;
import com.artezio.buyndrive.domain.Users;
import com.artezio.buyndrive.service.CarserviceService;
import com.artezio.buyndrive.service.CityService;
import com.artezio.buyndrive.service.CountryService;
import com.artezio.buyndrive.service.UserService;
import com.artezio.buyndrive.service.impl.CapchaServiceImpl;
import com.artezio.buyndrive.validator.CarServiceRegisterValidator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.*;

/**
 * User: spolyakov Date: 26.07.12 Time: 12:38
 */
@Controller
@RequestMapping("/carservicePage")
public class UserPageController {

    protected final Log logger = LogFactory.getLog(RegistrationController.class);
    
    @Autowired
    private CountryService countryService;
    
    @Autowired
    private CityService cityService;
    
    @Autowired
    private CarserviceService carserviceService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private CarServiceRegisterValidator carserviceRegisterValidator;

    @RequestMapping("/carservices/toInsert")
    public ModelAndView insert(Map<String, Object> map, Model model,
            HttpServletRequest servletRequest, HttpSession session) {
        logger.info("/toInsert");

        session.setAttribute("carservice", null);
        model.addAttribute("carservice", new Carservice());
        model.addAttribute("countryList", countryService.getAll());

        return new ModelAndView("registerService");
    }

    @RequestMapping("/carservices/edit/{id}")
    public ModelAndView details(@PathVariable("id") Long id,
            Model model, HttpSession httpSession) {

        Carservice carservice = carserviceService.findById(id);

        model.addAttribute("carservice", carservice);

        httpSession.setAttribute("carservice", carservice);
        model.addAttribute("countryList", countryService.getAll());

        model.addAttribute("cityListR", cityService
                .getCitiesByCountID(carservice.
                getIdCity().getIdCountry()));
        
        return new ModelAndView("registerService");
    }

    @RequestMapping("/carservices/list")
    public ModelAndView list(Model model,
            HttpServletRequest servletRequest, HttpSession session) {
        logger.info("/toInsert");
        Users user = (Users) session.getAttribute("user");

        model.addAttribute("carservice", new Carservice());
        model.addAttribute("listCarservices", carserviceService.getList(user));
        return new ModelAndView("carservicesList");
    }

    @RequestMapping(value = "/carservices/save", method = RequestMethod.POST)
    public ModelAndView save(@ModelAttribute("carservice") Carservice carservice,
            BindingResult result, HttpSession session, Model model) {
        logger.info("Trying to makeReg...");

        Users user = (Users) session.getAttribute("user");
        carserviceRegisterValidator.validate(carservice, result);

        if (!result.hasErrors()) {
            Carservice carserviceSave = (Carservice) session.getAttribute("carservice");
            carservice.setIdUsers(user);
            carservice.setRating(0);

            if (carserviceSave != null) {
                carservice.setId(carserviceSave.getId());
                carserviceService.saveOrUpdate(carservice);
            } else {
                carserviceService.add(carservice);
            }

            //return "registerService";
            return new ModelAndView("redirect:/carservicePage/carservices/list");
        }
        model.addAttribute("carservice", carservice);
        model.addAttribute("countryList", countryService.getAll());
        return new ModelAndView("registerService");

    }

    @RequestMapping(value = "/carservices/getCityList", method = RequestMethod.GET)
    public ModelAndView getCityList(Map<String, Object> map, HttpServletRequest servletRequest) {

        try {
            Long id = Long.valueOf(servletRequest.getParameter("country_id"));
            Country country = countryService.findById(id);
            List list = cityService.getCitiesByCountID(country);
            map.put("cityListR", list);
        } catch (Exception e) {
            logger.error(e);
        }

        return new ModelAndView("cityList");
    }

    @RequestMapping("/carservices/delete/{id}")
    public ModelAndView delete(@PathVariable("id") Long id,
            Model model, HttpSession httpSession) {
        carserviceService.delete(id);
        return new ModelAndView("redirect:/carservicePage/carservices/list");
    }
    
    @RequestMapping("/editProfile")
    public ModelAndView editProfile(Model model, HttpSession httpSession) {
        model.addAttribute("user", (Users) httpSession.getAttribute("user"));
        return new ModelAndView("editProfile");
    }
    
    @RequestMapping("/saveProfile")
    public ModelAndView saveProfile(Model model, HttpSession httpSession,
    @ModelAttribute("user") Users user, BindingResult result) {
        
        Users userSave = (Users) httpSession.getAttribute("user");
        String confPass = model.("confPassword");

        registrationValidator.confirmPass(admin, result, confPass);

        if (result.hasErrors()) {
            logger.error("Adding error!");

            model.addAttribute("user", new Admin());
            return new ModelAndView("editProfile");
        }
        return new ModelAndView("editProfile");
    }
}
